package cn.genmer.test.security.rpc.v2.rpc.transport;

import cn.genmer.test.security.rpc.v2.rpc.Dispatcher;
import cn.genmer.test.security.rpc.v2.rpc.protocol.GContent;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;

public class GHttpRpcHandler extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletInputStream in = req.getInputStream();
        ObjectInputStream oin = new ObjectInputStream(in);
        try {
            GContent reqContent = (GContent)oin.readObject();

            String serviceName = reqContent.getName();
            String methodName = reqContent.getMethodName();
            Object res = null;
            try{
                Object obj = Dispatcher.getDispatcher().get(serviceName);
                Class<?> clazz = obj.getClass();
                Method method = clazz.getMethod(methodName, reqContent.getParameterTypes());
                res = method.invoke(obj,reqContent.getArgs());
            }catch (Exception e){
                e.printStackTrace();
            }

            GContent responseContent = new GContent();
            // 设置返回信息
            responseContent.setRes(res);
//            byte[] contentByte = SerialUtil.serialObject(responseContent);

            ServletOutputStream outputStream = resp.getOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(responseContent);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
}
